import Singleton from '../Base/Singleton'
import { ApiMsgEnum, IApiPlayerJoinReq } from '../Common'
import { Connection } from '../Core'
import { Player } from './Player'
import { RoomManager } from './RoomManager'

// 资源加载
export class PlayerManager extends Singleton {
  static get Instance() {
    return super.GetInstance<PlayerManager>()
  }

  nextPlayerID = 1
  // 玩家集合
  players: Set<Player> = new Set()
  // id 映射 对应玩家
  idMapPlayer: Map<number, Player> = new Map()

  // 创建
  createPlayer({ nickname, connection }: IApiPlayerJoinReq & { connection: Connection } /*交叉类型 */) {
    const player = new Player({ id: this.nextPlayerID++, nickname, connection })
    this.players.add(player)
    this.idMapPlayer.set(player.id, player)
    return player
  }
  // 销毁
  removePlayer(id: number) {
    const player = this.idMapPlayer.get(id)
    if (player) {
      const { rid } = player
      if (rid) {
        const room = RoomManager.Instance.idMapRoom.get(rid)
        if (!room) throw new Error('房间不存在')
        room.leave(player.id)
        // 同步房内信息
        room.async()
        // 同步房间信息
        RoomManager.Instance.syncRooms()
      }
      this.players.delete(player)
      this.idMapPlayer.delete(player.id)
    }
  }
  // 获取单个-->执行过滤
  getPlayerView({ id, nickname, rid }: Player) {
    return { id, nickname, rid }
  }
  // 获取所有玩家
  getPlayersView(players: Set<Player> = this.players) {
    return [...players].map(p => this.getPlayerView(p))
  }

  // 同步所有玩家列表
  syncPlayers() {
    for (const player of this.players) {
      player.connection.sendMsg(ApiMsgEnum.MsgPlayerList, {
        list: this.getPlayersView(),
      })
    }
  }
}
